import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:wechat_kit/wechat_kit.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/pay/ali_pay_utils.dart';
import 'package:tracker/common/pay/model/order_info_req.dart';
import 'package:tracker/common/pay/wxpay_utils.dart';
import 'package:tracker/common/widget/pay_dialog_widget.dart';
import 'package:tracker/pages/home/flowcard/model/card_packages_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:material_dialogs/material_dialogs.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 套餐类型枚举
enum PackageType {
  /// 流量叠加包
  additionalPackage,

  /// 主套餐
  mainPackage,
}

/// 充值套餐页面
class ChargePage extends ConsumerStatefulWidget {
  const ChargePage({super.key});
  @override
  ConsumerState<ChargePage> createState() => _ChargePageState();
}

class _ChargePageState extends ConsumerState<ChargePage> {
  bool showLoading = true;
  CardPackagesData cardPackagesData = CardPackagesData();

  PayDialogWidget payDialogWidget = PayDialogWidget();
  final alipayUtils = AliPayUtils();
  final wxpayUtils = WxpayUtils();

  _showLoading() {
    return Center(
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  _fetchCardPackages() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final queryParams = {
      'iccid': deviceInfo.iccid,
      'imei': deviceInfo.imei,
      // 'iccid': '89860479042070143369',
      // 'imei': '58058888888',
    };
    final res =
        await get<CardPackagesResp, CardPackagesResp>('', queryParameters: queryParams, decodeType: CardPackagesResp());
    setState(() {
      showLoading = false;
    });
    res.when(success: (CardPackagesResp resp) {
      if (resp.code == 200) {
        setState(() {
          showLoading = false;
          cardPackagesData = resp.data!;
        });
      }
    }, failure: (String msg, int code) {
      setState(() {
        showLoading = false;
      });
    });
  }

  Widget _buildBodyView() {
    return Column(
      children: [
        // 流量叠加包
        _buildAdditionalPackageView(),
        // 主套餐
        _buildMainPackageView(),
      ],
    );
  }

  Widget _buildAdditionalPackageView() {
    return Container(
      width: MediaQuery.of(context).size.width,
      margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          // 标题
          const Row(
            children: [
              Text(
                '流量叠加包',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ],
          ),
          const SizedBox(
            height: 12,
          ),
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: cardPackagesData.additionalPackageInfo?.length ?? 0,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 20,
              crossAxisSpacing: 20,
              childAspectRatio: 1.2,
            ),
            itemBuilder: (BuildContext context, int index) {
              return _buildAdditionalPackageItemView(index);
            },
          ),
        ],
      ),
    );
  }

  _buildAdditionalPackageItemView(int index) {
    final packageInfo = cardPackagesData.additionalPackageInfo![index];
    final money = NumUtils.formatNum(packageInfo.price);
    final consumption = NumUtils.formatNum(packageInfo.consumption);
    return GestureDetector(
      onTap: () {
        _showPackageInfoDialog(packageInfo, PackageType.additionalPackage);
      },
      child: Container(
        padding: const EdgeInsets.all(4),
        decoration: BoxDecoration(
          color: ColorUtils.hexToColor('#deebff'),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Text(
              '${consumption}M/${packageInfo.packageName}',
              style: TextStyle(fontSize: 14, color: AppTheme.themeConfig.primaryColor),
              maxLines: 1,
            ),
            Text(
              '￥${money}',
              style: TextStyle(fontSize: 17, color: AppTheme.themeConfig.primaryColor, fontWeight: FontWeight.bold),
              maxLines: 1,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMainPackageView() {
    return Container(
      width: MediaQuery.of(context).size.width,
      margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          // 标题
          const Row(
            children: [
              Text(
                '主套餐',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ],
          ),
          const SizedBox(
            height: 12,
          ),
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: cardPackagesData.mainPackageInfo == null ? 0 : 1,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 20,
              crossAxisSpacing: 20,
              childAspectRatio: 1.2,
            ),
            itemBuilder: (BuildContext context, int index) {
              return _buildMainPackageItemView(index);
            },
          ),
        ],
      ),
    );
  }

  Widget _buildMainPackageItemView(int index) {
    final mainPackageInfo = cardPackagesData.mainPackageInfo!;
    final money = NumUtils.formatNum(mainPackageInfo.price);
    final consumption = NumUtils.formatNum(mainPackageInfo.consumption);
    return GestureDetector(
      onTap: () {
        _showPackageInfoDialog(mainPackageInfo, PackageType.mainPackage);
      },
      child: Container(
        padding: const EdgeInsets.all(4),
        decoration: BoxDecoration(
          color: ColorUtils.hexToColor('#deebff'),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Text(
              '${consumption}M/${mainPackageInfo.packageName}',
              style: TextStyle(fontSize: 14, color: AppTheme.themeConfig.primaryColor),
              maxLines: 1,
            ),
            Text(
              '￥${money}',
              style: TextStyle(fontSize: 17, color: AppTheme.themeConfig.primaryColor, fontWeight: FontWeight.bold),
              maxLines: 1,
            ),
          ],
        ),
      ),
    );
  }

  /// 弹窗显示套餐信息
  _showPackageInfoDialog(PackageInfo packageInfo, PackageType packageType) {
    final consumption = NumUtils.formatNum(packageInfo.consumption);
    final packageName = packageInfo.packageName;
    final price = NumUtils.formatNum(packageInfo.price);
    Dialogs.bottomMaterialDialog(
        color: Colors.white,
        context: context,
        customView: StatefulBuilder(builder: (context, setState) {
          return Container(
            width: double.infinity,
            padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  packageName ?? '',
                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                const SizedBox(
                  height: 20,
                ),
                Text(
                  '数量：${consumption}M',
                  style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.infoTextColor),
                ),
                const SizedBox(
                  height: 8,
                ),
                Text(
                  '生效时间：立即生效',
                  style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.infoTextColor),
                ),
                // 虚线
                Divider(
                  height: 28,
                  thickness: 1,
                  color: ColorUtils.hexToColor('#e5e5e5'),
                ),
                Text(
                  '充值号码：${cardPackagesData.cardNo}',
                  style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.infoTextColor),
                ),
                const SizedBox(
                  height: 8,
                ),
                Text(
                  '价格：${price}',
                  style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.infoTextColor),
                ),
              ],
            ),
          );
        }),
        actions: [
          TextButton(
            onPressed: () {
              _showPayDialog(packageInfo, packageType);
            },
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
              shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(20))),
              minimumSize: MaterialStateProperty.all(const Size(double.infinity, 40)),
            ),
            child: const Text(
              '订购',
              style: TextStyle(fontSize: 16, color: Colors.white),
            ),
          )
        ]);
  }

  /// 选择支付方式
  _showPayDialog(PackageInfo packageInfo, PackageType packageType) {
    payDialogWidget.showPayDialog(context, '${packageInfo.price}', onConfirm: (payType) {
      _doBuy(packageInfo, packageType, payType);
    });
  }

  /// 点击订购
  _doBuy(PackageInfo packageInfo, PackageType packageType, PayType payType) {
    packageInfo.packageType = packageType == PackageType.mainPackage ? 1 : 2;
    final deviceInfo = ref.watch(deviceInfoProvider);
    // 支付方式
    final payAccount = PayUtils.getPayAccount(payType);
    final payTypeParams = PayUtils.getPayType(payType);
    final orderInfoReq = OrderInfoReq(
      imei: deviceInfo.imei,
      payType: payTypeParams,
      payAccount: payAccount,
      orderType: 1,
      flowPackage: packageInfo,
    );
    XLogger.debug('orderInfoReq: ${orderInfoReq.toJson()}');
    if (payType == PayType.alipay) {
      alipayUtils.createOrder(orderInfoReq);
    } else if (payType == PayType.wechat) {
      wxpayUtils.createOrder(orderInfoReq);
    } else if (payType == PayType.wechatUnion) {
      wxpayUtils.createMiniAppOrder(orderInfoReq);
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _fetchCardPackages();
    });
    // 支付宝支付监听
    alipayUtils.listenPay((resp) {
      context.pop();
      XLogger.info('流量卡支付结果：${resp.resultStatus}');
      if (resp.isSuccessful) {
        // 支付成功
        ToastUtils.showSimpleDialog(context, title: '提示', content: '套餐购买成功', confirmTitle: '好的', confirmCallback: () {
          // 关闭当前页面
          context.pop();
        });
      } else {
        // 支付失败
        ToastUtils.showToast('支付失败');
      }
    });
    // 微信支付监听
    // wxpayUtils.registerWechatResp((resp) {
    //   context.pop();
    //   XLogger.info('流量卡支付结果：${resp}');
    //   if (resp.isSuccessful) {
    //     // 支付成功
    //     ToastUtils.showSimpleDialog(
    //         context,
    //         title: '提示',
    //         content: '套餐购买成功',
    //         confirmTitle: '好的',
    //         confirmCallback: () {
    //           // 关闭当前页面
    //           context.pop();
    //         }
    //     );
    //   } else {
    //     // 支付失败
    //     ToastUtils.showToast('支付失败');
    //   }
    // });
    wxpayUtils.registerWechatResp((resp) {
      if (resp is WechatLaunchMiniProgramResp) {
        XLogger.info('拉起小程序: ${resp.errorCode} ${resp.errorMsg}, isSuccessful: ${resp.isSuccessful}');
        XLogger.info('拉起小程序 exMsg: ${resp.extMsg}');
        if (resp.isSuccessful) {
          // 支付成功
          ToastUtils.showSimpleDialog(context, title: '提示', content: '购买成功', confirmTitle: '好的', confirmCallback: () {
            // 关闭当前页面
            context.pop();
          });
        } else {
          // 支付失败
          ToastUtils.showToast('支付失败');
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    alipayUtils.dispose();
    wxpayUtils.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '充值套餐',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
      body: showLoading ? _showLoading() : _buildBodyView(),
    );
  }
}
